﻿using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using BLL.CustomAttribute;

namespace BLL.Utility
{
    public class ModelHelper<T> where T : class
    {
        private static string GetDisplayName(PropertyInfo pi, object obj)
        {
            var display = pi.GetCustomAttributes(typeof(DisplayAttribute), false);
            var name = display.Any() ? display.Cast<DisplayAttribute>().Single().Name : pi.Name;
            var value = pi.GetValue(obj, null);
            return string.Format("{0}:{1};", name, value);
        }

        public static string AutoCreateModelString(object obj)
        {
            var properties = typeof(T)
                .GetProperties()
                .Where(p => p.IsDefined(typeof(StringPropertyAttribute), false)).ToList();
            var result = new StringBuilder();
            foreach (var propertyInfo in properties)
            {
                result.Append(GetDisplayName(propertyInfo, obj));
            }
            return result.ToString();
        }
    }
}